package com.atguigu.stack;

import java.util.Scanner;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        boolean loop=true;
        Scanner scanner = new Scanner(System.in);
        while(loop){
            System.out.println("show:展示栈");
            System.out.println("push:入栈");
            System.out.println("pop:出栈");
            System.out.println("exit:结束程序");
            System.out.println("请输入操作:");
            String next = scanner.next();
            switch (next){
                case "show":
                    stack.show();
                    break;
                case "push":
                    System.out.println("请输入入栈的值");
                    int i = scanner.nextInt();
                    stack.push(i);
                    break;
                case "pop":
                    try{
                        int pop = stack.pop();
                        System.out.printf("出栈值为%d\n",pop);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case "exit":
                    loop=false;
                    break;
            }
        }
        scanner.close();
        System.out.println("程序结束");
    }
}

class ArrayStack{
    private final int maxSize;
    private final int[] stack;
    private int top=-1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
    }

    public boolean isFull(){
        return this.top==maxSize-1;
    }

    public boolean isEmpty(){
        return this.top==-1;
    }

    public void show(){
        if (isEmpty()) {
            System.out.println("栈空...");
            return;
        }
        for (int i = this.top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }

    public void push(int val){
        if (isFull()) {
            System.out.println("栈满...");
            return;
        }
        this.stack[++this.top]=val;
    }

    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈空...");
        }

        return this.stack[this.top--];
    }
}
